package com.hbnu.ysc.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * jdbc工具类
 */
public class JdbcUtil {
    //数据源对象(连接池)
    private static DataSource dataSource;

    //加载数据库连接信息到DataSource
    static {
        try {
            //创建Properties属性文件
            Properties properties=new Properties();
            //将Properties属性文件转换为字符输入流
            InputStream inputStream=JdbcUtil.class.getResourceAsStream("/db.properties");
            //加载流
            properties.load(inputStream);
            //创建连接池对象
            dataSource= DruidDataSourceFactory.createDataSource(properties);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 从数据库中取出一个connection对象
     * @return
     */
    public static Connection getConnection(){
        Connection connection=null;
        try {
            connection=dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 关闭连接（Connection连接对象必须在最后关闭）
     * @param connection Connection连接对象
     * @param pstm 编译执行对象
     * @param result 结果集
     */
    public static void closeConnection(Connection connection,PreparedStatement pstm, ResultSet result){
        try {
            if(result != null){
                result.close();
            }
            if(pstm != null){
                pstm.close();
            }
            if(connection != null){
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
